package com.sunny;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class SumTask extends RecursiveTask<Long> {

    private int threshold = 0;
    private long[] array;
    private int s;
    private int t;

    public SumTask(long[] array, int s, int t) {
        this.array = array;
        this.s = s;
        this.t = t;
        System.out.println(s+" " +t);
    }

    @Override
    protected Long compute() {
        if(t-s<=threshold){
            long res = 0;
            for(int i=s; i<=t; i++){
                res += array[i];
            }
            return res;
        }
        int mid = (s+t)>>1;
        SumTask sub1 = new SumTask(array, s, mid);
        SumTask sub2 = new SumTask(array, mid+1, t);
//        invokeAll(sub1, sub2); // 从结果上看，与下面两行代码作用相同
        sub1.fork();
        sub2.fork();
        long s1 = sub1.join();
        long s2 = sub2.join();
        return s1+s2;
    }

    public static void main(String[] args) {

        long[] array = {1,2,3,4,5,6,7,8,9,10};
        ForkJoinPool tp = new ForkJoinPool(4);
        ForkJoinTask<Long> fj = new SumTask(array, 0, array.length-1);
        long res = tp.invoke(fj);
        System.out.println(res);
    }
}
